// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const cartDB = cloud.database().collection("cart")
// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.op) {
    case "add":
      return cartDB.add({
        data: {
          s_id: event.s_id,
          g_id: event.g_id,
          number: event.number,
          parameter: event.parameter
        }
      }).then(res => { return res }).catch(console.error)
    case "delete":
      return cartDB.doc(event.id).remove().then(res => { return res }).catch(console.error)
    case "update":
      return cartDB.doc(event.id).update({
        data: {
          s_id: event.s_id,
          g_id: event.g_id,
          number: event.number,
          parameter: event.parameter
        }
      }).then(res => { return res }).catch(console.error)
    case "select":
      switch (event.key) {
        case "_id":
          return cartDB.where({
            _id: event.value
          }).get().then(res => { return res }).catch(console.error)
        case "s_id":
          return cartDB.where({
            s_id: event.value
          }).get().then(res => { return res }).catch(console.error)
        case "g_id":
          return cartDB.where({
            g_id: event.value
          }).get().then(res => { return res }).catch(console.error)
        case "multi_s_id":
          //in方法查询数据
          const _ = cloud.database().command
          return cartDB.where({
            s_id: _.in(event.value)
          }).get().then(res => { return res }).catch(console.error)
      }
  }
}